package com.affectu.common.base;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import com.affectu.common.AffectuException;

/**
 * Sep 21, 2008
 * 
 * @author daniel nathan
 */
public abstract class UtilBase {

	protected Logger logger = Logger.getLogger(this.getClass().getName());

	protected final Lock lock = new ReentrantLock();

	public UtilBase() {
		logger.setLevel(Level.WARNING);
	}

	protected void log(String message) {
		logger.info(message);
	}

	public void logException(Throwable throwable) {
		logAffectuException(throwable, "");
	}

	public void logAffectuException(Throwable throwable, String message) {
		AffectuException ae = new AffectuException(message, throwable);
		ae.printStackTrace();
	}

	protected String removeHtmlTags(String input) {
		if (input == null || input.trim().equals("")) {
			return "";
		}
		// 去掉所有html元素,
		String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll(
				"<[^>]*>", "");
		str = str.replaceAll("[(/>)<]", "");
		return str;
	}

	protected String filterHtmlTags(String input, int length) {
		String str = this.removeHtmlTags(input);
		int len = str.length();
		if (len <= length) {
			return str;
		} else {
			str = str.substring(0, length);
			str += "......";
		}
		return str;
	}

	protected String getSuffix(String inputString) {
		String suffix = inputString;
		if (inputString.indexOf(".") != -1) {
			suffix = inputString.substring(inputString.lastIndexOf(".") + 1,
					inputString.length());
		}
		this.log(suffix);
		return suffix;
	}

	protected int getIntValue(String input) {
		int value = 0;
		try {
			if (this.isNumeric(input)) {
				value = Integer.valueOf(input).intValue();
			}
		} catch (Exception ex) {
			this.logAffectuException(ex, "转换出错:" + input);
		}
		return value;
	}

	public boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}
}
